<?php
namespace app\backend\controller;
use app\backend\model\Admin;
use app\BaseController;
use think\captcha\facade\Captcha;
use think\facade\Session;
use think\middleware\SessionInit;
use think\facade\View;
use app\backend\model\Response;
class Login extends BaseController
{
    public function index() {
        return view();
    }

    public function verify() {
        return Captcha::create('verify');
    }

    private function checkcaptcha($captcha) {
        if (!Captcha::check($captcha)) {
            return false;
        } else {
            return true;
        }
    }

    private function searchUsernameAndPwd($username, $password): ?Admin
    {
        if ($username == null || $password == null || strlen($username) == 0 || strlen($password) == 0) {
            return null;
        }
        return Admin::where(['name' => $username, 'password'=>md5($password)])->findOrEmpty();
    }

    public function login() {
        $username = input('post.username');
        $password = input('post.password');
        $captcha = input('post.captcha');
        $response = new Response();
        if ($this->checkcaptcha($captcha)) {
            $admin = $this->searchUsernameAndPwd($username, $password);
            if ($admin != null && !$admin->isEmpty()) {
                $response->success();
                $response->msg = "登录成功";
                Session::set('id', $admin->id);
                Session::set('name', $admin->name);
            } else {
                $response->msg = "用户名或密码错误";
            }
        } else {
            $response->msg = "验证码错误";
        }
        echo $response->toJson();
    }


}